package lily.phs.healthedu;

import java.util.ArrayList;
import java.util.Calendar;

import lily.phs.child.ImageList;
import lily.phs.database.Constants;
import lily.phs.epidemic.Epidemic;
import lily.phs.epidemic.EpidemicList;
import lily.phs.epidemic.EpidemicList.myThread;

import lily.phs.mental.MentalerDetails;
import lily.phs.mental.MentalerList;
import lily.phs.object.EpidemicRecord;
import lily.phs.object.HereTipa;
import lily.phs.object.PersonInfo;

import lily.phs.urh.PeopleScrollActivity;
import lily.phs.urh.R;
import lily.phs.vaccination.VaccinationActivity;
import lily.phs.vaccination.VaccinationScrollActivity;
import lily.ui.bookshelf.CaseLevelView;
import lily.ui.bookshelf.ProfileView;
import android.text.InputType;
import android.util.Log;
import android.view.View.OnClickListener;
import lily.ui.bookshelf.WindowSizeUtil;
import lily.ui.control.MyPopupWindow;
import lily.ui.control.SearchPopupWindow;
import lily.ui.panel.Panel;
import lily.ui.panel.Panel.OnPanelListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.MeasureSpec;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Healthedu extends Activity implements OnClickListener,Constants,OnPanelListener,OnItemClickListener,OnFocusChangeListener
{
	private View view;
	private ArrayList<CaseLevelView> AllLevels;
	private LinearLayout ll_Content;
	private int ProfilesSUM;//档案总数
	private int ProfilesInOneLevel;//每层最多可放置的档案数
	private String[] allProfiles;
	private ProgressDialog mpDialog;
	 AlertDialog ad;
	 MyPopupWindow mPopupWindow;
	private int idList[];
	//private EditText et_name,et_sex,et_born,et_guardian_name,et_relation,et_guardian_phone,et_create_people,et_create_date;
	private SearchPopupWindow sPopupWindow;
	private Button leftBtn,rightBtn2,rightBtn;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		LayoutInflater factory=(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view=factory.inflate(R.layout.profilecase, null);
		final TextView tvTitle = (TextView)view.findViewById(R.id.title);
		tvTitle.setText("教育活动");
		
		ll_Content=(LinearLayout)view.findViewById(R.id.shelves_content);
		AllLevels=new ArrayList<CaseLevelView>();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		
		
		mpDialog=new ProgressDialog(Healthedu.this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mpDialog.setMessage("正在加载···");
		mpDialog.setIndeterminate(false);
		mpDialog.setCancelable(true);
		mpDialog.show();
		new myThread(handler,"",1).start();//query
		
		GridView grid = (GridView)this.findViewById(R.id.bottomgrid);
		String[] menus = new String[]{"添加","刷新","查询"};
		int[] images = new int[]{R.drawable.add_files,R.drawable.fresh,R.drawable.search_file};
		ImageList adapter = new ImageList(this,images,menus);
		grid.setAdapter(adapter);
		
		
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
				switch (arg2) {
				case 0:				
					//LayoutInflater factory = LayoutInflater.from(getBaseContext());
		            //View x = factory.inflate(R.layout.layout_x1, null);
		            Intent intent=new Intent();
		            Bundle bd = new Bundle();
		            bd.putInt("state", 2);//新建活动记录表
		            intent.putExtras(bd);
		            intent.setClass(Healthedu.this,Jkjy.class);
		            startActivityForResult(intent,1);
		            finish();
		         		         
		            /**new AlertDialog.Builder(getBaseContext())
		            .setTitle("")
		            .setIcon(null)
		            .setView(x)
		            .setPositiveButton("", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					})
					.setNegativeButton("", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					})
		            .create().show();*/

		                   
		                break;
					
				case 1:
					mpDialog = new ProgressDialog(Healthedu.this);  
					mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
					mpDialog.setMessage("正在加载...");  
					mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
					mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
					mpDialog.show();
					new myThread(handler,"",2).start();
					break;
				case 2:
					
					sPopupWindow = new SearchPopupWindow(getBaseContext());		
					sPopupWindow.showAtLocation(findViewById(R.id.title_left_btn), Gravity.CENTER, 0, 0);
					sPopupWindow.setAnimationStyle(R.anim.i_slide_in_left);
					final Button bt=sPopupWindow.getBt();
					final EditText et=sPopupWindow.getEt();
					bt.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							//searchContentView(et.getText().toString());
							mpDialog = new ProgressDialog(Healthedu.this);  
							mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
							mpDialog.setMessage("正在刷新...");  
							mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
							mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
							mpDialog.show();
							new myThread(handler,et.getText().toString(),1).start();
						}
						
					});
				default:
					break;
				}
			}

		});
		leftBtn = (Button) findViewById(R.id.title_left_btn);
        rightBtn = (Button) findViewById(R.id.title_right_btn);
        rightBtn2 = (Button) findViewById(R.id.title_right_btn2);
        leftBtn.setText("后退");
        rightBtn.setVisibility(View.INVISIBLE);
        rightBtn2.setVisibility(View.INVISIBLE);
        leftBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
        	
        });
	}
	//添加新的层
	private void addNewLevel() {
		// TODO Auto-generated method stub
		CaseLevelView newcaseLevelView = new CaseLevelView(this);
		AllLevels.add(newcaseLevelView);
		ll_Content.addView(
				newcaseLevelView,newcaseLevelView.LevelWidth,newcaseLevelView.LevelHeight);//
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY),
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelHeight, MeasureSpec.EXACTLY));
//		Log.i(TAG, ""+MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY));
//		System.out.println("addLevel:"+newcaseLevelView.LevelWidth+","+newcaseLevelView.LevelHeight);
		setContentView(view);
		
	}
	/**@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	//	int i=v.getId();
		Intent editprofile = new Intent();
		Bundle bd = new Bundle();
		bd.putInt("Profile_id", v.getId());//待编辑档案的ID
		bd.putInt("father", MODULE_FATHER);
		bd.putInt("call", MODULE_LIST);
		editprofile.putExtras(bd);
		editprofile.setClass(Healthedu.this, VaccinationScrollActivity.class);
		startActivity(editprofile);
		overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
		
	}*/

	/******************************************************************/
	/**
	 * @return 每一层可放的档案数
	 */
    private int getProfilesInOneLevel() {
    	// TODO Auto-generated method stub
		
    	WindowSizeUtil util = new WindowSizeUtil(this);
		ProfileView newProfile = new ProfileView(this);
		return util.ScreenWidth/newProfile.FileWidth;
		
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch(resultCode){
		case RESULT_OK:{
			
			initContentView();
			break;
		}
		}
	}
    
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		finish();
		overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
	}
	private void searchContentView(String name, int state) {
		// TODO Auto-generated method stub
    	
    	Cursor cursor = null;
//		name.replace(" ", "");
		//此处没有判断state，没有查询功能，以后需要加上
//		if(state==1){
//		cursor = this.managedQuery(CONTENT_URI_TB25,null, 
//				HETI_NAME+" LIKE '%"+name+"%'", null, null);
//		}
//		if(state==1){
//			
//		}
		cursor = this.managedQuery(CONTENT_URI_TB25,null, 
				null, null, null);
		ProfilesSUM = cursor.getCount();
		//ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
//        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        idList=new int[ProfilesSUM];
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
//        	cursor.getInt(cursor.getColumnIndex(_ID));
        	idList[i]=cursor.getInt(cursor.getColumnIndex(_ID));
        	allProfiles[i] = cursor.getString(cursor.getColumnIndex(HERE_THEME));
        	Log.i("edu", "allProfiles["+i+"]="+allProfiles[i]+";");
        	
        }	
	} 
    
    
    private void addNewProfileInLevel(int level, String ProfileName, int profileId) {
		// TODO Auto-generated method stub
    	ProfileView newProfile = new ProfileView(this);
		String s=""+profileId;
		newProfile.button.setText(ProfileName);//档案名称
		newProfile.button.setId(profileId);//档案编号
		newProfile.button.setContentDescription(s);
		System.out.println("addFile:name="+ProfileName+",id="+profileId);
		newProfile.button.setOnClickListener(this);
		
		if(level>=AllLevels.size()){
			addNewLevel();
		}
		AllLevels.get(level).addView(
				newProfile,//,newProfile.FileWidth,newProfile.FileHeight);
				MeasureSpec.makeMeasureSpec(newProfile.FileWidth, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(newProfile.FileHeight, MeasureSpec.EXACTLY));

//		System.out.println("addFile:"+newProfile.FileWidth+","+newProfile.FileHeight);
		setContentView(view);		
	}
    
    
    public void initContentView(){

    	
		Cursor cursor = this.managedQuery(CONTENT_URI_TB25,null, null, null, null);
		ProfilesSUM = cursor.getCount();
		ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
//        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	int ID = cursor.getInt(cursor.getColumnIndex(_ID));
        	//HereTipa ht=new HereTipa(this);
        	//ht.selectNameAndCode(ID);
        	allProfiles[i] =cursor.getString(cursor.getColumnIndex(HERE_THEME));// "新生儿"+i;//cursor.getString(cursor.getColumnIndex(HETI_NAME));
        	
            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
//            System.out.println("selectedLevel="+selectedLevel);
            addNewProfileInLevel(selectedLevel,allProfiles[i],ID);
        }	
	}
    public class myThread extends Thread{
		private Handler handler;
		private String str;
		private int state;
		public myThread(Handler handler,String str,int state){
			this.handler=handler;
			this.str=str;
			this.state=state;
		}
		public void run(){
			try{
				Looper.getMainLooper();
				sleep(200);
				Message msg=handler.obtainMessage();
				if(this.state<10){
					searchContentView(this.str,this.state);
					
					msg.what=1;
				}
				else {
					createProfile();
					searchContentView(this.str,this.state);
					msg.what=2;
				}
					handler.sendMessage(msg);
				
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
	}
	private final Handler handler =new Handler(Looper.getMainLooper()){
		public void handleMessage(Message msg){
			if(msg.what==1){
				for(int i=0;i<AllLevels.size();i++){
					AllLevels.get(i).removeAllViews();
				}
				ProfilesInOneLevel=getProfilesInOneLevel();
				if(ProfilesInOneLevel<1){
					ProfilesInOneLevel=4;
				}
				for(int i=0;i<allProfiles.length;i++){
					int selectedLevel=i/ProfilesInOneLevel; //新档案应放置的层
					addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
				}
				mpDialog.cancel();
			}
			else if(msg.what==2){
				ad.cancel();
    			for(int i=0;i<AllLevels.size();i++){
    				AllLevels.get(i).removeAllViews();
    			}
    			ProfilesInOneLevel = getProfilesInOneLevel();
    			if(ProfilesInOneLevel<1){
    				ProfilesInOneLevel=4;
    			}
    			for(int i=0;i<allProfiles.length;i++){
    	            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
//    	            System.out.println("selectedLevel="+selectedLevel);
    	            addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
    	        }
    			mpDialog.cancel();
			}
		}
	};
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		
	}
	public void createProfile() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onPanelClosed(Panel panel) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onPanelOpened(Panel panel) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent editprofile = new Intent();
		Bundle bd = new Bundle();
		bd.putInt("Profile_id", v.getId());//待编辑档案的ID
		bd.putInt("state",1);//查看活动记录表
		bd.putInt("father", MODULE_FATHER);
		bd.putInt("call", MODULE_LIST);
		editprofile.putExtras(bd);
		editprofile.setClass(Healthedu.this, Jkjy.class);
		startActivity(editprofile);
		finish();
		overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
	}
}

